package jwebtester.business.services.impl;

import java.util.Map;

import javax.faces.context.FacesContext;

import jwebtester.business.services.SessionMapService;
import jwebtester.business.utils.SessionMapKeys;

import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;

import domain.entities.User;

@Service
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public class SessionMapServiceImpl implements SessionMapService {

	@SuppressWarnings("unchecked")
	@Override
	public <T> T get(final String key) {
		final Map<String, Object> sessionMap = getSessionMap();
		return (T) sessionMap.get(key);
	}

	@Override
	public <T> void put(final String key, final T value) {
		final Map<String, Object> sessionMap = getSessionMap();
		sessionMap.put(key, value);
	}

	private Map<String, Object> getSessionMap() {
		return FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
	}

	@Override
	public int getCurrentUserID() {
		final User user = getCurrentUser();
		return user.getId();
	}

	@Override
	public int getCurrentOrganizationID() {
		final User user = getCurrentUser();
		return user.getOrganization().getId();
	}
	
	private User getCurrentUser(){
		return (User)get(SessionMapKeys.CURRENT_USER);
	}
}
